{extend name="main"}
{block name="style"}
<style type="text/css">
    .w-60px{width: 60px;}
    .w-80px{width: 80px;}
    .w-150px{width: 150px;}
    .wx-wechat{width: 320px;height: 560px;margin: 0 auto;position: relative;background-color: #eee;border:solid 1px #ddd;}
    .wx-wechat .wx-wechat-header{width: 100%;height:64px;line-height:64px;background-color: #343434;color: #fff;text-align: center;}
    .borderSize{
        border-left: 3px solid #f59A23;
    }
</style>
{/block}
{block name="body"}
<div class="bg-white p-3">

    <div class="mb-3">
        <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="创建模板通知" name="createNotify"></el-tab-pane>
            <el-tab-pane label="模板通知列表" name="getNotify"></el-tab-pane>
        </el-tabs>
    </div>

    <div class="flex" v-if="activeName=='createNotify'">
        <div class="flex-1 pr-3">

            <div  style="background-color:#fff7f0;box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);color: #f59A23;margin-bottom: 50px;">
                <el-button type="text" @click="()=>{showQuestion=!showQuestion}"><i class="el-icon-question m-2"></i>什么是模板通知？</el-button>
                <div style="flex: 1 1 0%;padding: 20px" v-if="showQuestion">
                    <div style="margin-bottom: 27px">
                        <h5 class="borderSize">什么是模板通知？</h5>
                        <p>为任意粉丝推送模板消息，支持跳转任意链接和已关联小程序</p>
                    </div>
                    <div style="margin-bottom: 27px">
                        <h5 class="borderSize">可以用来做什么？</h5>
                        <p><i class="el-icon-user"></i>不占公众号的群发次数推送</p>
                        <p>不占用公众号群发次数推送模板消息，支持添加跳转外链和小程序</p>
                    </div>
                    <h5 class="borderSize">使用注意事项</h5>
                    <p>模板通知是系统为公众号更精准地运营粉丝提供的一项服务，有以下注意事项：</p>
                    <ul>
                        <li class="my-2">
                            <span>1、仅支持认证服务号使用此功能。</span>
                        </li>
                        <li>
                            <span>2、请严格遵守微信运营规范，不得利用模板消息接口从事以下行为：</span>
                            <ul>
                                <li class="my-2">
                                    <span>2.1 发布内容与服务场景不一致（含标题、关键词）的模板消息</span>
                                </li>
                                <li>
                                    <span>2.2 发送广告营销类模板消息</span>
                                </li>
                                <li>
                                    <span>2.3 发送红包、卡券、优惠券、代金券、会员卡之类的模板消息</span>
                                </li>
                            </ul>
                        </li>
                        <li class="my-2">
                            <span>3、频繁发送相同内容或性质的模板消息，对用户造成骚扰。包括但不限于模板消息功能限制、公众号封禁等情况，后果由运营者自行承担，与本平台无关。</span>
                        </li>
                    </ul>
                </div>
            </div>

            <el-form :model="form" @submit.native.prevent="submitForm" :rules="rules" ref="form" label-width="120px" :label-position="labelPosition">

                <el-form-item label="历史发送" >
                    <el-select v-model="HistorySends" class="col-9 col-sm-9 pl-0 pr-0" clearable placeholder="请选择" @change="selectHistory">
                        <el-option
                                v-for="item in HistorySendsData"
                                :key="item.id"
                                :label="item.title"
                                :value="item.id"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="标题：" prop="title">
                    <el-input v-model="form.title" class="col-9 col-sm-9 pl-0 pr-0"  placeholder="标题不会跟随推送，仅用于系统后台场景进行区分"></el-input>
                </el-form-item>



                <el-form-item label="选择模板" >
                    <el-select v-model="WebSiteValue" class="col-9 col-sm-9 pl-0 pr-0" clearable placeholder="请选择" @change="selectWebSite">
                        <el-option
                                v-for="item in WebSiteTemplate"
                                :key="item.tplid"
                                :label="item.title"
                                :value="item.tplid"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>



                <el-form-item  v-for="(v,index) in templateItem.item_data"  :label="v.title" >
                    <el-row>
                        <el-input type="textarea" v-model="v.value" class="col-9 col-sm-9 pl-0 pr-0" maxlength="200" show-word-limit
                                  :autosize="{ minRows: 2, maxRows: 10}" ></el-input>
                        <el-color-picker v-model="v.color" size="small"></el-color-picker>
                    </el-row>
                </el-form-item>

                <el-form-item label="跳转链接" prop="toWhereType">
                    <el-radio v-model="form.toWhereType" label="1">跳转链接(支持外链)</el-radio>
                    <el-radio v-model="form.toWhereType" label="2">小程序</el-radio>
                </el-form-item>

                <el-form-item  v-if="form.toWhereType==1" label="URL" prop="url">
                    <el-input v-model="form.url" class="col-9 col-sm-9 pl-0 pr-0"></el-input>
                </el-form-item>
                <div v-else>
                    <el-form-item label="小程序app ID">
                        <el-input v-model="form.appId" class="col-9 col-sm-9 pl-0 pr-0"></el-input>
                    </el-form-item>
                    <el-form-item label="跳转页面路径">
                        <el-input v-model="form.pagePath" class="col-9 col-sm-9 pl-0 pr-0"></el-input>
                    </el-form-item>
                    <el-form-item label="备用链接">
                        <el-input v-model="form.standbyUrl" class="col-9 col-sm-9 pl-0 pr-0"></el-input>
                    </el-form-item>
                </div>
                <el-form-item label="推送给谁" prop="toUserType">
                    <el-radio v-model="form.toUserType" label="1">粉丝标签</el-radio>
                    <el-radio v-model="form.toUserType" label="2">全部粉丝</el-radio>
                </el-form-item>
                <el-form-item v-if="form.toUserType==1" label="粉丝标签分组" prop="fansGroupTag"
                              label-width="120px">
                    <el-select v-model="form.fansGroupTag" @change="getFansGroup" filterable multiple default-first-option :multiple-limit="6" placeholder="请选择">
                        <el-option
                                v-for="item in fansGroup"
                                :key="item.id"
                                :label=item.name+"("+item.count+"人)"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-else>
                    <label v-if="formData.fansTotal<0">请确认当前公众号类型为已认证的服务号</label>
                    <label v-else>预计将推送给全部粉丝共{{formData.fansTotal}}个粉丝</label>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm('form')">立即保存</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="flex-1 pl-3">
            <el-divider >模板预览</el-divider>
            <div class="wx-wechat">
                <div class="wx-wechat-header">
                    {:config('web.name')}
                </div>
                <div class="wx-wechat-body p-3">
                    <div class="bg-white rounded border p-2">
                        <div>{{templateItem.title}}</div>
                        <div class="flex" v-for="(v,index) in templateItem.item_data">
                            <div class="small" v-if="v.value=='first'" :style="{color:v.color}" v-html="conGetHtml(v.value)"></div>
                            <div v-else>
                                <el-row>
                                <span class="w-60px small text-secondary">
                                    {{v.title}}：
                                </span>
                                    <span class="small" :style="{color:v.color}">
                                    {{v.value}}
                                </span>
                                </el-row>
                            </div>
                        </div>
                        <div class="flex" v-if="form.remark">
                            <!--<div class="w-60px small text-secondary">-->
                            <!--    备注:-->
                            <!--</div>-->
                            <div class="flex-1 small" :style="{color:form.remark_color}" v-html="conGetHtml(form.remark)">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div v-else>
        <el-card  class="box-card my-3" v-for="(item,index) in notifyList" >
            <div slot="header" class="clearfix">
                <span>{{item.title}}</span>
                <!--                <el-button style="float: right; padding: 3px 0" type="text">操作按钮</el-button>-->
            </div>
            <el-row>
                <el-label>群发总人数：</el-label>
                <el-label>{{item.to_user_num}}</el-label>
            </el-row>

            <el-row>
                <el-label>送达人数：</el-label>
                <el-label>{{item.to_user_send}}</el-label>
            </el-row>
            <el-row>
                <el-label>发送状态：</el-label>
                <span v-if="item.to_user_send==0 && item.err_msg != '' " >
                    <el-tooltip effect="dark" placement="top">
                         <div slot="content" v-if="item.err_msg==null">未获取到具体的失败原因</div>
                         <div slot="content" v-else>{{item.err_msg}}</div>
                      <el-tag type="danger" size="small">  发送失败</el-tag>
                    </el-tooltip>
                </span>
                <el-tag type="success" v-else-if="item.to_user_send>0" size="small">发送成功</el-tag>
                <el-tag v-else size="small" >发送中</el-tag>
            </el-row>
            <el-row>
                <el-label>群发对象：</el-label>
                <el-label v-if="item.to_user_type==2">全部粉丝</el-label>
                <el-label v-else>分组发送</el-label>
            </el-row>
            <el-row>
                <el-label>创建时间：</el-label>
                <el-label>{{item.create_time}}</el-label>
            </el-row>
            <el-row>
                <el-label>模板标题：</el-label>
                <el-label>{{item.tpl_title}}</el-label>
                <el-button type="text" @click="isShowDetail">详情<i :class="elIconArrowRight"></i></el-button>
            </el-row>
            <div style="box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);width: 25%;margin-left: 5%" v-if="showDetail">
                <div class="m-1" style="padding:15px 5px 15px 5px">
                    <p>{{item.tpl_title}} </p>
                    <p v-for="(vi,vo) in item.data" :style="{color:vi.color}">{{vi.value}}</p>
                </div>
            </div>
        </el-card>
        <div class="table-responsive py-3 text-center">
            <el-pagination
                    background
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="search.page"
                    :page-sizes="[10,50,100,200]"
                    :page-size="search.pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="search.total">
            </el-pagination>
        </div>
    </div>

</div>
{/block}

{block name="script"}
<script type="text/javascript">
    // var WebSiteTemplateData=JSON.parse('{:json_encode($WebSiteTemplate)}');
    var WebSiteTemplateData= {:json_encode($WebSiteTemplate,JSON_UNESCAPED_UNICODE)};

    var initiative={$initiative|raw};
    var sendCount={$sendCount|raw};
    var formData={
        first:'',
        first_color:'#343434',
        remark:'',
        remark_color:'#343434',
        url:'',
        status:1,
        fansGroupTag:[],
        //发送给谁的类型
        toUserType:'2',
        //跳转外链或小程序
        toWhereType:'1',
        //全部粉丝的总数
        fansTotal:-1,
        to_user_num:0,
        //小程序Id
        appId:"",
        //小程序跳转页面
        pagePath:"/pages/common/home/home",
        //备用链接
        standbyUrl:"",
        title:"",

    };
</script>
<script type="text/javascript">
    var vm=new Vue({
        el:'#app',
        data:{
            view:XYBase.view,
            labelPosition:'right',
            form:formData,
            HistorySends:'',
            HistorySendsData:initiative,
            WebSiteTemplate:WebSiteTemplateData,
            fansGroup:[],
            WebSiteValue:'',
            templateItem:[],
            tplId:'',
            tplTitle:'',
            notifyList:[],
            showQuestion:false,
            repeat_disabled:false,
            showDetail:false,
            elIconArrowRight:"el-icon-arrow-right",
            activeName:"createNotify",
            sendCount:sendCount,
            ItemData:{title:'',value:'',color:'#343434'},
            search:{
                title:'',
                ajax:false,
                pid:"0",
                page:1,
                total:0,
                pageSize:10
            },
            rules: {
                alias: [
                    { required: true, message: '请输入Alias', trigger: 'blur' },
                ],
                title: [
                    { required: true, message: '请输入名称', trigger: 'blur' },
                ],
                tplid: [
                    { required: true, message: '请输入模板ID', trigger: 'blur' },
                ],
                first: [
                    { required: true, message: '请输入First', trigger: 'blur' },
                ],
                remark: [
                    { required: true, message: '请输入Remark', trigger: 'blur' },
                ],
                status: [
                    { required: true, message: '请选择状态', trigger: 'blur' },
                ],
            }
        },
        watch:{
            view:XYBase.viewWatch,
        },
        created(){
            XYBase.created(this);
        },
        methods:{
            isShowDetail(){
                this.showDetail=!this.showDetail;
                if (this.showDetail){
                    this.elIconArrowRight="el-icon-arrow-down";
                }else {
                    this.elIconArrowRight="el-icon-arrow-right";

                }
            },
            handleSizeChange(val) {
                this.search.page=1;
                this.search.pageSize=val;
                this.handleClick({name:"getNotify"});
            },
            handleCurrentChange(val) {
                this.search.page=val;
                // let tab={name:"getNotify"};
                this.handleClick({name:"getNotify"});
            },
            handleClick(tab) {
                if (tab.name=="getNotify"){
                    this.activeName==tab.name
                    _this=this;
                    //获取列表
                    $.ajax({
                        url:"/getInitiativeNotify",
                        type:'get',
                        data:_this.search,
                        dataType:'json',
                        success:function(ret){
                            if (ret) {
                                if(ret.code == 0){
                                    ret.data.data.map((item)=>{
                                        item.data=JSON.parse(item.data);
                                        return item;
                                    })
                                    _this.notifyList=ret.data.data
                                    console.log(_this.notifyList)
                                    _this.search.total=ret.data.total;
                                }else{
                                    XYBase.msg(ret.msg);
                                }
                            }else{
                                XYBase.error(XYBase.config.system_network_error)
                            }
                        },
                        error:function(err){
                            XYBase.error(XYBase.config.system_network_error)
                        }
                    });
                }
            },
            getFansGroup:function(value){
                console.log(value)
                value.map((item)=>{
                    this.fansGroup.map((i)=>{
                        if(item==i.id){
                            this.form.to_user_num+=i.count;
                        }
                    })
                })
            },
            selectWebSite:function (value){
                // console.log(value)
                // templateItem
                _this=this;

                _this.WebSiteTemplate.forEach((item)=>{
                    if (item.tplid==value){
                        _this.templateItem=item;
                        var fir=[{"title":"首选项",'name':"first","value":"first","color":"#343434"}]
                        _this.templateItem.item_data=fir.concat(JSON.parse(item.item_data))
                        _this.templateItem.item_data.push({"title":"备注",'name':"remark","value":"remark","color":"#343434"})
                        _this.tplId=item.tplid
                        _this.tplTitle=item.title
                        return;
                    }
                })
                //   console.log( _this.templateItem);
            },
            selectHistory:function(varlue){
                if(varlue!=undefined && varlue!=""){
                    let selectHis=[];
                    this.HistorySendsData.map((item)=>{
                        if(item.id==varlue){
                            selectHis=item;
                            return;
                        }

                    })
                    this.form.title=selectHis.title;
                    this.WebSiteValue=selectHis.wt_id
                    _this=this;
                    _this.WebSiteTemplate.forEach((item)=>{
                        if (item.tplid==selectHis.wt_id){
                            _this.templateItem=item;
                            if(typeof item.item_data=='string'){
                                item.item_data=JSON.parse(item.item_data);
                                var fir=[{"title":"首选项",'name':"first","value":"first","color":"#343434"}]
                                _this.templateItem.item_data=fir.concat(item.item_data)
                                _this.templateItem.item_data.push({"title":"备注",'name':"remark","value":"remark","color":"#343434"})
                            }
                            // var fir=[{"title":"首选项","value":"first","color":"#343434"}]
                            // _this.templateItem.item_data=fir.concat(item.item_data)
                            // _this.templateItem.item_data.push({"title":"备注","value":"remark","color":"#343434"})
                            _this.tplId=item.tplid
                            _this.tplTitle=item.title
                            return;
                        }
                    })
                    let dat=JSON.parse(selectHis.data)
                    // console.log(selectHis)
                    // console.log(dat)
                    for(i in dat ){
                        _this.templateItem.item_data.map((item)=>{
                            let value=item.value.replace(/[\{\}\.DATA+]/g, '');
                            if(value==i){
                                item.value=dat[i].value;
                                item.color=dat[i].color;
                            }
                        })
                    }
                }

            },
            conGetHtml:function(str){
                if (str) {
                    return str.replace(/\n/g, '<br/>');
                }else{
                    return '';
                }
            },

            setDefaultColor(val){
                if (!val)
                    this.ItemData.color='#343434';
            },
            submitForm:function (){
                if(this.form.toUserType=='2'){
                    this.form.to_user_num=this.form.fansTotal;
                }
                _this=this;
                if (this.sendCount>0){
                    this.$confirm('检测到您今天已推送过'+_this.sendCount+'次，因微信接口频率限制，继续推送可能会导致推送失败或公众号封禁等情况', '推送提示', {
                        confirmButtonText: '继续推送',
                        cancelButtonText: '取消推送',
                        type: 'warning'
                    }).then(() => {
                        $.ajax({
                            url:"/templateNotify",
                            data:{data:_this.templateItem.item_data,template_id:_this.tplId,form:_this.form,tpl_title:_this.tplTitle},
                            type:'post',
                            dataType:'json',
                            success:function(ret){
                                if (ret) {
                                    if(ret.code == 0){
                                        XYBase.success(ret.msg);
                                        setTimeout(() => {
                                            window.location.href='/templateNotify';
                                        }, 1000);
                                    }else{
                                        XYBase.error(ret.msg);
                                    }
                                }else{
                                    XYBase.error(XYBase.config.system_network_error)
                                }
                            },
                            error:function(err){
                                XYBase.error(XYBase.config.system_network_error)
                            }
                        });
                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消推送'
                        });
                    });
                }else{
                    $.ajax({
                        url:"/templateNotify",
                        data:{data:_this.templateItem.item_data,template_id:_this.tplId,form:_this.form,tpl_title:_this.tplTitle},
                        type:'post',
                        dataType:'json',
                        success:function(ret){
                            if (ret) {
                                if(ret.code == 0){
                                    XYBase.success(ret.msg);
                                    setTimeout(() => {
                                        window.location.href='/templateNotify';
                                    }, 1000);
                                }else{
                                    XYBase.error(ret.msg);
                                }
                            }else{
                                XYBase.error(XYBase.config.system_network_error)
                            }
                        },
                        error:function(err){
                            XYBase.error(XYBase.config.system_network_error)
                        }
                    });
                }

            },
            getFansUser(){
                _this=this;
                $.ajax({
                    url:"/getFansForMP",
                    type:'post',
                    dataType:'json',
                    success:function(ret){
                        if (ret) {
                            if (ret.code==0) {
                                _this.form.fansTotal = ret.data.fansTotal;
                                _this.fansGroup =JSON.parse(ret.data.fansGroup).tags;
                                _this.form.appId=ret.data.appid
                                _this.form.standbyUrl=ret.data.url
                                _this.form.url=ret.data.url

                            }else {
                                _this.$alert(ret.msg, '跳转首页', {
                                    confirmButtonText: '确定',
                                    callback: action => {
                                        window.location.href='/';

                                    }
                                });
                            }

                        }else{
                            XYBase.error(XYBase.config.system_network_error)
                        }
                    },
                    error:function(err){
                        XYBase.error(XYBase.config.system_network_error)
                    }
                });
            }
        }
    });
    $(function(){
        vm.getFansUser();
        reloadWindowSize();
        $(window).resize(function(){
            reloadWindowSize();
        });
    });
    function reloadWindowSize (argument) {
        var winW=$(window).width();
        if(winW <= 576){
            vm.labelPosition='top';
        }else{
            vm.labelPosition='right';
        }
    }
</script>
{/block}